package com.huluspace.nosqlredis.controller;

import com.huluspace.nosqlredis.dto.LoginRequest;
import com.huluspace.nosqlredis.dto.LoginResponse;
import com.huluspace.nosqlredis.model.User;
import com.huluspace.nosqlredis.security.JwtUtil;
import com.huluspace.nosqlredis.service.JwtAuthService;
import com.huluspace.nosqlredis.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

  // 注入
  private final UserService userService;
  private final JwtAuthService jwtAuthService;
  private final JwtUtil jwtUtil;
  public AuthController(UserService userService, JwtAuthService jwtAuthService, JwtUtil jwtUtil) {
    this.userService = userService;
    this.jwtAuthService = jwtAuthService;
    this.jwtUtil = jwtUtil;
  }

  // 用户注册
  @PostMapping("/register")
  public String register(@RequestBody User user) {
    return userService.register(user);
  }

  // 用户登录
  @PostMapping("/login")
  public LoginResponse login(@RequestBody LoginRequest request) {
    return userService.login(request.username, request.password);
  }

  // 退出或下线
  @PostMapping("/logout")
  public ResponseEntity<String> logout(HttpServletRequest request) {
    String token = jwtUtil.extractToken(request);
    jwtAuthService.invalidateToken(token);
    return ResponseEntity.ok("已退出登录");
  }

  @GetMapping("/status")
  public ResponseEntity<?> getUserInfo(HttpServletRequest request) {
    String token = jwtUtil.extractToken(request);
    if (jwtAuthService.isTokenInvalid(token)) { // 判断token是否失效
      return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户未登录");
    }
    String username = jwtUtil.extractUserName(token);
    return ResponseEntity.ok(Map.of("username", username));
  }

}

